/* http://github.com/mindmup/bootstrap-wysiwyg */
/*global jQuery, $, FileReader*/
/*jslint browser:true*/
(function ($) {
	'use strict';
	var readFileIntoDataUrl = function (fileInfo) {
		var loader = $.Deferred(),
			fReader = new FileReader();
		fReader.onload = function (e) {
			loader.resolve(e.target.result);
		};
		fReader.onerror = loader.reject;
		fReader.onprogress = loader.notify;
		fReader.readAsDataURL(fileInfo);
		return loader.promise();
	};
	$.fn.cleanHtml = function () {
		var html = $(this).html();
		return html && html.replace(/(<br>|\s|<div><br><\/div>|&nbsp;)*$/, '');
	};
	$.fn.wysiwyg = function (userOptions) {
		var editor = this,
			selectedRange,
			options,
			toolbarBtnSelector,
			updateToolbar = function () {
				if (options.activeToolbarClass) {
					$(options.toolbarSelector).find(toolbarBtnSelector).each(function () {
						var command = $(this).data(options.commandRole);
						if (document.queryCommandState(command)) {
							$(this).addClass(options.activeToolbarClass);
						} else {
							$(this).removeClass(options.activeToolbarClass);
						}
					});
				}
			},
			execCommand = function (commandWithArgs, valueArg) {
				var commandArr = commandWithArgs.split(' '),
					command = commandArr.shift(),
					args = commandArr.join(' ') + (valueArg || '');
				document.execCommand(command, 0, args);
				updateToolbar();
			},
			bindHotkeys = function (hotKeys) {
				$.each(hotKeys, function (hotkey, command) {
					editor.keydown(hotkey, function (e) {
						if (editor.attr('contenteditable') && editor.is(':visible')) {
							e.preventDefault();
							e.stopPropagation();
							execCommand(command);
						}
					}).keyup(hotkey, function (e) {
						if (editor.attr('contenteditable') && editor.is(':visible')) {
							e.preventDefault();
							e.stopPropagation();
						}
					});
				});
			},
			getCurrentRange = function () {
				var sel = window.getSelection();
				if (sel.getRangeAt && sel.rangeCount) {
					return sel.getRangeAt(0);
				}
			},
			saveSelection = function () {
				selectedRange = getCurrentRange();
			},
			restoreSelection = function () {
				var selection = window.getSelection();
				if (selectedRange) {
					try {
						selection.removeAllRanges();
					} catch (ex) {
						document.body.createTextRange().select();
						document.selection.empty();
					}

					selection.addRange(selectedRange);
				}
			},
            cleanHtml=function(){
                var isrun=window.confirm("此操作会删除所有格式并且不可恢复\n确认继续吗？");
                if(!isrun)
                {
                    return false;
                }
                var ohtml='old';
                var newhtml='new';
                while(newhtml!=ohtml)
                {
                    ohtml=$(editor).html();
                $(editor).find("*").each(function(){
                    var reattr=['href','name','target','src','data-web','data-zipimg','colspan','rowspan','valign','type'];//要保留的属性列表
                    var tagname=$(this)[0].tagName.toLowerCase();
                    var retag={//要转换的标签映射表
                        blockquote:'div'
                    };
                    var normtag={//要保留的标签列表
                        p:1,
                        div:1,
                        span:1,
                        a:1,
                        img:1,
                        h1:1,
                        h2:1,
                        h3:1,
                        h4:1,
                        h5:1,
                        h6:1,
                        b:1,
                        font:1,
                        i:1,
                        strong:1,
                        table:1,
                        tbody:1,
                        tr:1,
                        th:1,
                        td:1,
                        embed:1,
                        object:1,
                    };

                    if(retag[tagname])
                        {
                            var str=$(this).html();
                            var o=document.createElement(retag[tagname]);
                            $(o).html(str);
                            $(this).replaceWith($(o));
                    }
                    if(!normtag[tagname])
                    {
                        var cent="";
                        if($(this).text()==$(this).html())
                        {
                            cent='<p>'+$(this).html()+'</p>';
                        }else{
                            cent=$(this).html();
                        }
                        $(this).replaceWith(cent);
                    }

                    var obj=$(this)[0];
                    var objattrs=obj.attributes;
                    for(var i in objattrs)
                    {
                        var attrname=objattrs[i].name;
                        if($.inArray(attrname,reattr)==-1)
                        {
                            $(this).removeAttr(attrname);
                        }
                    }
                    if($(this).html()=="" && (tagname=="hr" || tagname=="br"))
                    {
                        $(this).remove();
                    }
                });
                    newhtml=$(editor).html();
                }
            },
            insertHtml=function(str){
                if($.browser().browser.msie)
                {
                    document.selection.createRange().pasteHTML(str);
                }else{
                    execCommand('insertHtml',str);
                }
            },
			insertFiles = function (files) {
				editor.focus();
				$.each(files, function (idx, fileInfo) {
					if (/^image\//.test(fileInfo.type)) {
						$.when(readFileIntoDataUrl(fileInfo)).done(function (dataUrl) {

                            var o=document.createElement('img');
                                o.src=dataUrl;
                            var zipimgo=jic.zipimg3(o,50000);
                            var ret=execCommand('insertimage',zipimgo);
                            $(editor).find("img").attr('data-web','lemge_pic');
						}).fail(function (e) {
							options.fileUploadError("file-reader", e);
						});

					} else {
						options.fileUploadError("unsupported-file-type", fileInfo.type);
					}
				});
			},
			markSelection = function (input, color) {
				restoreSelection();
				if (document.queryCommandSupported('hiliteColor')) {
					document.execCommand('hiliteColor', 0, color || 'transparent');
				}
				saveSelection();
				input.data(options.selectionMarker, color);
			},
            //插入上传图片时候的替换loading
            insertImgloading=function(exid){

            },
			bindToolbar = function (toolbar, options) {
				toolbar.find(toolbarBtnSelector).click(function () {
                    var thiscommand=$(this).data(options.commandRole);
                    if(thiscommand=='_my_cleanHtml')
                    {
                        restoreSelection();
                        editor.focus();
//                        execCommand('removeFormat');
                        var cont= $(editor).html();
                        cleanHtml();
                        saveSelection();
                    }else if(thiscommand=='_my_addlink'){
                        restoreSelection();
                        editor.focus();

                        var seltxt='123';
                        seltxt=mygetSelectedContents();
                        $('#'+$(this).data('txtid')).val(seltxt);
                        saveSelection();
                        
                    }else if(thiscommand=='_my_addanchor'){
                        restoreSelection();
                        editor.focus();

                        var seltxt='';
                        seltxt=window.getSelection();
//                        seltxt= $.trim(seltxt);
                        if($.trim(seltxt)=='')
                        {
                            seltxt='&rarr;';
                        }
                        var n=Math.random();
                        var pre='_wwwlemgecom_';
                        var tmpstr='<a href="#'+pre+n+'" name="'+pre+n+'" id="'+pre+n+'">'+seltxt+'</a>';
                        insertHtml(tmpstr);
                        saveSelection();
                    }else{
                        restoreSelection();
                        editor.focus();
                        execCommand($(this).data(options.commandRole));
                        saveSelection();
                    }
				});


				toolbar.find('[data-toggle=dropdown]').click(restoreSelection);


                //添加链接
                $('#_cl_btn').on('click',function(){
                    restoreSelection();
                    var _cl_link=$('#_cl_link').val();
                    var _cl_text=$('#_cl_text').val();
                    $('#_cl_link').val('');
                    $('#_cl_text').val('');
                    if(!_cl_link)
                    {
                        return false;
                    }
                    if(_cl_link.indexOf('http://')!=0 && _cl_link.indexOf('https://')!=0 && _cl_link.indexOf('ftp://')!=0 )
                    {
                        _cl_link='http://'+_cl_link;
                    }
                    editor.focus();
                    if(!_cl_text)
                    {
                        _cl_text=_cl_link;
                    }
                    var str='<a href="'+_cl_link+'" target="_blank">'+_cl_text+'</a>';

                    // alert(str);
                    insertHtml(str);

                    saveSelection();
                });
                //添加链接
                //添加视频
                $('#_addflash_btn').on('click',function(){
                    restoreSelection();
                    var _cl_link=$('#_falsh_link').val();
                    $('#_cl_link').val('');
                    if(!_cl_link)
                    {
                        return false;
                    }
                    if(_cl_link.indexOf('http://')!=0 && _cl_link.indexOf('https://')!=0 && _cl_link.indexOf('ftp://')!=0 )
                    {
                        _cl_link='http://'+_cl_link;
                    }
                    editor.focus();
                    var str='<embed src="'+_cl_link+'" type="application/x-shockwave-flash"></embed>';
0
                    insertHtml(str);
                    saveSelection();
                });
                //添加视频
                
                //添加图片
                $('#_insert_img').on('click',function(){
                    upf.clk(function(exid){
//                        alert(exid);
                        restoreSelection();
                        editor.focus();
                        var loading_img="<img src='/img/15upload.gif' id='imgloading"+exid+"'/>";
                        insertHtml(loading_img);
                        saveSelection();
                    });
                    var str="";
                    upf.cusfunc=function(){
                        restoreSelection();
                        editor.focus();
                        var ret=upf.retdata;
                        if(ret.err && ret.err!=0)
                        {
                            alert(ret.emsg);
                        }else{
                            str="<img style='max-width: 100%' src='"+ret.val+"' /><br/>";
                        }
//                        insertHtml(str);
                        $("#imgloading"+ret.exinfo).replaceWith(str);
                        saveSelection();
                    }
                });
                //添加图片

                //清理格式

				toolbar.find('input[type=text][data-' + options.commandRole + ']').on('webkitspeechchange change', function () {
					var newValue = this.value; /* ugly but prevents fake double-calls due to selection restoration */
					this.value = '';
					restoreSelection();
					if (newValue) {
						editor.focus();
						execCommand($(this).data(options.commandRole), newValue,true);
					}
					saveSelection();
				}).on('focus', function () {
					var input = $(this);
					if (!input.data(options.selectionMarker)) {
						markSelection(input, options.selectionColor);
						input.focus();
					}
				}).on('blur', function () {
					var input = $(this);
					if (input.data(options.selectionMarker)) {
						markSelection(input, false);
					}
				});
				toolbar.find('input[type=file][data-' + options.commandRole + ']').change(function () {
					restoreSelection();
					if (this.type === 'file' && this.files && this.files.length > 0) {
						insertFiles(this.files);
					}
					saveSelection();
					this.value = '';
				});
			},
			initFileDrops = function () {
				editor.on('dragenter dragover', false)
					.on('drop', function (e) {
						var dataTransfer = e.originalEvent.dataTransfer;
						e.stopPropagation();
						e.preventDefault();
						if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
							insertFiles(dataTransfer.files);
						}
					});
			};
		options = $.extend({}, $.fn.wysiwyg.defaults, userOptions);
		toolbarBtnSelector = 'a[data-' + options.commandRole + '],button[data-' + options.commandRole + '],input[type=button][data-' + options.commandRole + ']';
		bindHotkeys(options.hotKeys);
		if (options.dragAndDropImages) {
			initFileDrops();
		}
		bindToolbar($(options.toolbarSelector), options);
		editor.attr('contenteditable', true)
			.on('mouseup keyup mouseout', function () {
				saveSelection();
				updateToolbar();
			});
		$(window).bind('touchend', function (e) {
			var isInside = (editor.is(e.target) || editor.has(e.target).length > 0),
				currentRange = getCurrentRange(),
				clear = currentRange && (currentRange.startContainer === currentRange.endContainer && currentRange.startOffset === currentRange.endOffset);
			if (!clear || isInside) {
				saveSelection();
				updateToolbar();
			}
		});
		return this;
	};
	$.fn.wysiwyg.defaults = {
		hotKeys: {
//			'ctrl+b meta+b': 'bold',
//			'ctrl+i meta+i': 'italic',
//			'ctrl+u meta+u': 'underline',
//			'ctrl+z meta+z': 'undo',
//			'ctrl+y meta+y meta+shift+z': 'redo',
//			'ctrl+l meta+l': 'justifyleft',
//			'ctrl+r meta+r': 'justifyright',
//			'ctrl+e meta+e': 'justifycenter',
//			'ctrl+j meta+j': 'justifyfull',
//			'shift+tab': 'outdent',
			'tab': 'indent'
		},
		toolbarSelector: '[data-role=editor-toolbar]',
		commandRole: 'edit',
		activeToolbarClass: 'btn-info',
		selectionMarker: 'edit-focus-marker',
		selectionColor: 'darkgrey',
		dragAndDropImages: true,
		fileUploadError: function (reason, detail) { console.log("File upload error", reason, detail); }
	};
}(window.jQuery));

//图片压缩
var jic = {
    /**
     * Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
     * @param {Image} source_img_obj The source Image Object
     * @param {Integer} quality The output quality of Image Object
     * @return {Image} result_image_obj The compressed Image Object
     */
    //质量压缩图片不变尺寸
    zipimg1: function(source_img_obj, quality, output_format){
        var mime_type = "image/jpeg";
        //if(output_format!=undefined && output_format=="png"){
        //    mime_type = "image/png";
        //}
		var eif=$("#_exinfo");
        var cvs = document.createElement('canvas');
        //naturalWidth真实图片的宽度
        cvs.width=source_img_obj.naturalWidth;
        cvs.height=source_img_obj.naturalHeight;

		eif.append("<hr/><div style='color:green;'>"+source_img_obj.src.length+source_img_obj.src.substr(0,300)+"</div>");

        var ctx = cvs.getContext("2d");
		ctx.drawImage(source_img_obj, 0, 0);
        var newImageData = cvs.toDataURL(mime_type, 0.01);
		eif.append("<hr/><div style='color:red;'>"+newImageData.length+newImageData.substr(0,300)+"</div>");
        return newImageData;
    },
    //质量压缩图片变尺寸
    zipimg2: function(source_img_obj, quality, output_format){
        var mime_type = "image/jpeg";
        if(output_format!=undefined && output_format=="png"){
            mime_type = "image/png";
        }
        var cvs = document.createElement('canvas');
        //naturalWidth真实图片的宽度
        cvs.width=source_img_obj.naturalWidth*(quality);
        cvs.height=source_img_obj.naturalHeight*(quality);
        var ctx = cvs.getContext("2d");
        ctx.scale(quality,quality);
        ctx.drawImage(source_img_obj, 0, 0);
        var newImageData = cvs.toDataURL(mime_type, quality);
        return newImageData;
    },
    //压缩图片大小到指定的src长度
    zipimg3:function(source_img_obj, le,output_format){
        var q=1;
        var o=source_img_obj;
        while(o.src.length>le)
        {
            o.src=jic.zipimg2(source_img_obj,q,output_format);
            q=q*0.9;
        }
        return o.src;
    },
    test:function(){}
}
//文件遮盖
var cov={
    covid:"_covid",
    altid:"_altid",
    altstr:"<div id='_cov_prog'></div><div class=''>正在载入...</div>",
    setcov:function(){
        var co=document.createElement('div');
        var ao=document.createElement('div');

        $("body")[0].appendChild(co);
        $("body")[0].appendChild(ao);

        $(co).attr('id',cov.covid);
        $(co).attr('style','display: none;position: fixed;top: 0;left: 0;z-index: 10;background-color: #000000;opacity: 0.5');
        $(ao).attr('id',cov.altid);
        $(ao).attr('style','display: none;position: fixed;top: 0;left: 0;z-index: 15;text-align: center;color:#ffffff');
        var w=$(window).innerWidth();
        var h=$(window).innerHeight();

        $(co).css('display','block');
        $(co).css('width',w);
        $(co).css('height',h);

        $(ao).css('display','block');
        $(ao).css('width',w);
        $(ao).html(cov.altstr);
        $(ao).css('padding-top',h*0.45);
        $(document).on('dblclick',"#"+cov.covid,function(){
            cov.remcov();
        });
        $(document).on('dblclick',"#"+cov.altid,function(){
            cov.remcov();
        });
    },
    progcov:function(){
        var si=window.setInterval(function(){
            var progbox=$("#_cov_prog");
            var n=progbox.html();
            if(n=='')
            {
                n=0;
            }
            n=parseFloat(n,2);
            if(n<50)
            {
                n=n+(Math.random()*0.1);
            }
            else if(n<70){
                n=n+(Math.random()*0.05);
            }
            else if(n<80){
                n=n+(Math.random()*0.02);
            }
            else if(n<90){
                n=n+(Math.random()*0.01);
            }
            else if(n<99){
                clearInterval(si);
            }
            n= n.toFixed(2);
            progbox.html(n+"%");
        },10)
    },
    remcov:function(){
        $("#"+cov.covid).remove();
        $("#"+cov.altid).remove();
    }
}


function mygetSelectedContents() {
    if (window.getSelection && window.getSelection().rangeCount) { //chrome,firefox,opera
        var range = window.getSelection().getRangeAt(0);
        var container = document.createElement('div');
        container.appendChild(range.cloneContents());
        return container.innerHTML;
        //return window.getSelection(); //只复制文本
    }
    else if (document.getSelection && window.getSelection().rangeCount) { //其他
        var range = window.getSelection().getRangeAt(0);
        var container = document.createElement('div');
        container.appendChild(range.cloneContents());
        return container.innerHTML;
        //return document.getSelection(); //只复制文本
    }
    else if (document.selection) { //IE特有的
        return document.selection.createRange().htmlText;
        //return document.selection.createRange().text; //只复制文本
    }
    return false;
}


